package f.f.people;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;

@WebServlet("/travels")
public class servlet extends HttpServlet{
    ArrayList<Stu> stus = new ArrayList<>();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Ren ren = new Ren();
        ren.setCode(200);
       ren.setData(mapper.writeValueAsString(stus));
        resp.getWriter().println(mapper.writeValueAsString(ren));
   }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        var mapper = new ObjectMapper();
        Stu stu = mapper.readValue(req.getReader(), Stu.class);
        String name = stu.getName();
        Ren ren = new Ren();
        if (stus.size() == 10) {
            ren.setCode(400);
            ren.setMsg("报名失败：人员已满！");
        } else {
            Iterator<Stu> it = stus.iterator();
            while (it.hasNext()) {
                Stu student = it.next();
                if (stu.getName().equals(name)) {
                    ren.setCode(400);
                    ren.setMsg("报名失败:" + name + "已存在！");
                }
            }
        }


        if (ren.getCode() != 400) {
            stus.add(stu);

            ZonedDateTime time = Instant.now().atZone(ZoneId.of("Asia/Shanghai"));

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            String timeStr = dtf.format(time);
            stu.setCreated(timeStr);
            ren.setCode(200);
            ren.setData("OK");

        }

        resp.getWriter().println(mapper.writeValueAsString(ren));

    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Stu student = mapper.readValue(req.getReader(), Stu.class);
        String name = student.getName();
        int size = stus.size();
        Ren ren = new Ren();

        Iterator<Stu> it = stus.iterator();
        while (it.hasNext()){
            Stu stu = it.next();
            if(stu.getName().equals(name)){
                it.remove();
            }
        }

        if(stus.size() == size){
            ren.setCode(400);
            ren.setMsg("删除的人不存在！");
        }else{
            ren.setCode(200);
            ren.setData("OK");
        }

        resp.getWriter().println(mapper.writeValueAsString(ren));
    }
}
